<!DOCTYPE html>
<html>

<head>
    <title>osm buildings demo</title>
    <script type="text/javascript" src="https://unpkg.com/dat.gui@0.7.6/build/dat.gui.min.js"></script>
    <link type="text/css" rel="stylesheet" href="https://unpkg.com/maptalks/dist/maptalks.css">
    <script type="text/javascript" src="https://unpkg.com/maptalks/dist/maptalks.js"></script>
    <script type="text/javascript" src="https://unpkg.com/@maptalks/gl/dist/maptalksgl.js"></script>
    <script type="text/javascript" src="https://unpkg.com/three@0.138.0/build/three.min.js"></script>
    <script type="text/javascript"
        src="https://unpkg.com/three@0.138.0/examples/js/libs/stats.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/maptalks.three@latest/dist/maptalks.three.js"></script>
    <style>
        html,
        body {
            margin: 0px;
            height: 100%;
            width: 100%;
        }

        #map {
            width: 100%;
            height: 100%;
            background-color: #000;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>

        var map = new maptalks.Map("map", {
            "center": [-74.01829947483418, 40.723447222207795], "zoom": 14, "pitch": 66.8, "bearing": 34.62762656250061,
            centerCross: true,
            doubleClickZoom: false,
            baseLayer: new maptalks.TileLayer('tile', {
                urlTemplate: 'http://{s}.tiles.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejh2N21nMzAxMmQzMnA5emRyN2lucW0ifQ.jSE-g2vsn48Ry928pqylcg',
                subdomains: ['a', 'b', 'c', 'd'],
                attribution: '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://mapbox.com/">mapbox</a>'
            })
        });

        // the ThreeLayer to draw buildings
        var threeLayer = new maptalks.ThreeLayer('t', {
            forceRenderOnMoving: true,
            forceRenderOnRotating: true
            // animation: true
        });

        var meshs = [];
        var material = new THREE.MeshPhongMaterial({ color: '#1e2b27', transparent: true });
        var highlightmaterial = new THREE.MeshBasicMaterial({ color: 'yellow', transparent: true, opacity: 0.5 });

        threeLayer.prepareToDraw = function (gl, scene, camera) {

            stats = new Stats();
            stats.domElement.style.zIndex = 100;
            document.getElementById('map').appendChild(stats.domElement);

            var light = new THREE.DirectionalLight(0xffffff);
            light.position.set(0, -10, 10).normalize();
            scene.add(light);

            scene.add(new THREE.AmbientLight(0xffffff));


            load();
        };
        const sceneConfig = {
            postProcess: {
                enable: true,
                antialias: { enable: true }
            }
        };
        const groupLayer = new maptalks.GroupGLLayer('group', [threeLayer], { sceneConfig });
        groupLayer.addTo(map);

        let idx = 0, total = 600;

        let polygons = [];
        let selectMesh = [];
        function load() {
            fetch('./data/ny/' + idx + '.json').then(res => res.json()).then(geojson => {
                geojson.forEach(feature => {
                    const geometry = feature.geometry;
                    const type = feature.geometry.type;
                    if (['Polygon', 'MultiPolygon'].includes(type)) {
                        const height = feature.height || feature.properties.height || 20;
                        const properties = feature.properties;
                        properties.height = height;
                        const polygon = maptalks.GeoJSON.toGeometry(feature);
                        polygon.setProperties(properties);
                        polygons.push(polygon);
                    }

                });
                if (polygons.length > 0) {
                    var mesh = threeLayer.toExtrudePolygons(polygons.slice(0, Infinity), { topColor: '#fff', interactive: false }, material);
                    threeLayer.addMesh(mesh);
                    meshs.push(mesh);
                    polygons = [];
                    //tooltip test
                    mesh.setToolTip('hello', {
                        showTimeout: 0,
                        eventsPropagation: true,
                        dx: 10
                    });

                    //infowindow test
                    mesh.setInfoWindow({
                        content: 'hello world',
                        title: 'message',
                        animationDuration: 0,
                        autoOpenOn: false
                    });

                    //event test
                    ['click', 'mousemove', 'empty', 'mouseout', 'mouseover', 'mousedown', 'mouseup', 'dblclick', 'contextmenu'].forEach(function (eventType) {
                        mesh.on(eventType, function (e) {
                            // console.log(e.type);
                            const select = e.selectMesh;
                            if (e.type === 'empty' && selectMesh.length) {
                                threeLayer.removeMesh(selectMesh);
                                selectMesh = [];
                            }

                            let data, baseObject;
                            if (select) {
                                data = select.data;
                                baseObject = select.baseObject;
                                if (baseObject && !baseObject.isAdd) {
                                    baseObject.setSymbol(highlightmaterial);
                                    threeLayer.addMesh(baseObject);
                                    selectMesh.push(baseObject);
                                }
                            }


                            if (selectMesh.length > 20) {
                                threeLayer.removeMesh(selectMesh);
                                selectMesh = [];
                            }


                            // override tooltip
                            if (e.type === 'mousemove' && data) {
                                const height = data.getProperties().height;
                                const tooltip = this.getToolTip();
                                tooltip._content = `height:${height}`;
                            }
                            //override infowindow
                            if (e.type === 'click' && data) {
                                const height = data.getProperties().height;
                                const infoWindow = this.getInfoWindow();
                                infoWindow.setContent(`height:${height}`);
                                if (infoWindow && (!infoWindow._owner)) {
                                    infoWindow.addTo(this);
                                }
                                this.openInfoWindow(e.coordinate);

                            }
                        });
                    });
                }
                idx++;
                if (idx <= total) {
                    setTimeout(() => {
                        load(idx);
                    }, 10);
                } else {
                    initGui();
                    animation();
                }
            });
        }

        function animation() {
            // layer animation support Skipping frames
            threeLayer._needsUpdate = !threeLayer._needsUpdate;
            if (threeLayer._needsUpdate) {
                threeLayer.redraw();
            }
            stats.update();
            requestAnimationFrame(animation);
        }

        function initGui() {
            var params = {
                add: true,
                color: '#3e35cf',
                show: true,
                opacity: 1,
                altitude: 0,
                animateShow: animateShow,
                interactive: false
            };
            var gui = new dat.GUI();
            gui.add(params, 'add').onChange(function () {
                if (params.add) {
                    threeLayer.addMesh(meshs);
                } else {
                    threeLayer.removeMesh(meshs);
                }
            });
            gui.addColor(params, 'color').name('building color').onChange(function () {
                material.color.set(params.color);
                meshs.forEach(function (mesh) {
                    mesh.setSymbol(material);
                });
            });
            gui.add(params, 'opacity', 0, 1).onChange(function () {
                material.opacity = params.opacity;
                meshs.forEach(function (mesh) {
                    mesh.setSymbol(material);
                });
            });
            gui.add(params, 'show').onChange(function () {
                meshs.forEach(function (mesh) {
                    if (params.show) {
                        mesh.show();
                    } else {
                        mesh.hide();
                    }
                });
            });
            gui.add(params, 'altitude', 0, 300).onChange(function () {
                meshs.forEach(function (mesh) {
                    mesh.setAltitude(params.altitude);
                });
            });
            gui.add(params, 'animateShow');
            gui.add(params, 'interactive').onChange(function () {
                meshs.forEach(function (mesh) {
                    mesh.options.interactive = params.interactive;
                });
            });
        }

        function animateShow() {
            meshs.forEach(function (mesh) {
                mesh.animateShow({
                    duration: 3000
                });
            });
        }


    </script>
</body>

</html>
